#include "myserver.h"

MyServer::MyServer(QObject *parent) : QTcpServer(parent)
{
    client_count=new int(0);
    qDebug()<<*client_count;
}

MyServer::~MyServer()
{
    delete client_count;
}

void MyServer::start_listen(const QString port)
{
    if(listen(QHostAddress::Any,port.toUInt()))
    {
        qDebug()<<"监听成功！";

    }
    else
        qDebug()<<"监听失败！";
}

void MyServer::incomingConnection(qintptr socketDescriptor)
{
    My_TcpClientSocket* mytcpclientsocket=new My_TcpClientSocket;
    //只要有新的连接就生成一个新的通信套接字
    TcpClientSocket* tcpClientSocket=new TcpClientSocket;
    //将新创建的通信套接字描述符指定为参数socketDescriptor
    tcpClientSocket->setSocketDescriptor(socketDescriptor);
    (*client_count)++;
    QString str("第"+QString::number(*client_count)+"个客户端");
    mytcpclientsocket->socket_name=str;
    mytcpclientsocket->m_tcpClientSocket=tcpClientSocket;
    //将这个套接字加入客户端套接字列表中
    m_tcpClientSocketList.append(mytcpclientsocket);
    //qDebug()<<tcpClientSocket;
    //接收到tcpclientsocket发送过来的消息
    connect(tcpClientSocket,SIGNAL(sigUpdateSever(QString)),this,SLOT(slotUpdateServer(QString)));
    //处理客户端掉线
    connect(tcpClientSocket,SIGNAL(sigClientDisconnect(qintptr)),this,SLOT(slotClientDisconnected(qintptr)));
    qDebug()<<"连接成功";
    emit send_socketname(str);
}

void MyServer::sendtoClient(QString socketname,QString msg)
{
    QByteArray ba;
    ba.append(msg);
    for(auto i:m_tcpClientSocketList)
    {
        if(i->socket_name==socketname)
            i->m_tcpClientSocket->write(ba);
    }
}

void MyServer::slotUpdateServer(QString sMsg)
{
    //sMsg就是服务端从客户端收到的消息
    //在这里对消息进行处理，根据需求来设计
    emit send_message(sMsg);
}

void MyServer::slotClientDisconnected(qintptr iSocketDescriptor)
{
    //如果有客户端断开连接，就将列表中的套接字删除
    for(auto i:m_tcpClientSocketList)
    {
        if(i->m_tcpClientSocket->socketDescriptor()==iSocketDescriptor)
        {
            m_tcpClientSocketList.removeAt(m_tcpClientSocketList.indexOf(i));            
            delete i->m_tcpClientSocket;
            delete i;
            //qDebug()<<"已释放内存";
            return;
        }
    }
    return;
}

